﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MySqlManager
{
    internal class CastableString
    {
        internal string BaseString { get; private set; }
        internal CastableString(object value)
        {
            BaseString = value.ToString();
        }

        public static implicit operator CastableString(string value)
        {
            return new CastableString(value);
        }

        public static implicit operator sbyte(CastableString value)
        {
            sbyte val;
            if (sbyte.TryParse(value.BaseString, out val))
                return val;
            throw new InvalidCastException();
        }

        public static implicit operator byte(CastableString value)
        {
            byte val;
            if (byte.TryParse(value.BaseString, out val))
                return val;
            throw new InvalidCastException();
        }

        public static implicit operator Int16(CastableString value)
        {
            Int16 val;
            if (Int16.TryParse(value.BaseString, out val))
                return val;
            throw new InvalidCastException();
        }

        public static implicit operator UInt16(CastableString value)
        {
            UInt16 val;
            if (UInt16.TryParse(value.BaseString, out val))
                return val;
            throw new InvalidCastException();
        }

        public static implicit operator Int32(CastableString value)
        {
            Int32 val;
            if (Int32.TryParse(value.BaseString, out val))
                return val;
            throw new InvalidCastException();
        }

        public static implicit operator UInt32(CastableString value)
        {
            UInt32 val;
            if (UInt32.TryParse(value.BaseString, out val))
                return val;
            throw new InvalidCastException();
        }

        public static implicit operator Int64(CastableString value)
        {
            Int64 val;
            if (Int64.TryParse(value.BaseString, out val))
                return val;
            throw new InvalidCastException();
        }

        public static implicit operator UInt64(CastableString value)
        {
            UInt64 val;
            if (UInt64.TryParse(value.BaseString, out val))
                return val;
            throw new InvalidCastException();
        }

        public static implicit operator byte[](CastableString value)
        {
            return Encoding.ASCII.GetBytes(value.BaseString);
        }
    }
}
